(function ($, owner) {
    /**
     * 用户登录
     **/
    owner.login = function (loginInfo, callback) {
        callback = callback || $.noop;
        loginInfo = loginInfo || {};
        loginInfo.account = loginInfo.account || '';
        loginInfo.password = loginInfo.password || '';
        if (loginInfo.account.length < 4) {
            return callback('账号最短为 4 个字符');
        }
        if (loginInfo.password.length < 6) {
            return callback('密码最短为 6 个字符');
        }
        mui.post("/site/login.html", loginInfo, function (data) {
            if (data.status === false) {
                return callback(data.msg);
            } else {
                window.location.href = data.url;
            }
        }, "json");
    };
    /*
     * 更新密码
     */
    owner.uppass = function (dataInfo, callback) {
        callback = callback || $.noop;
        dataInfo = dataInfo || {};
        dataInfo.oldpassword = dataInfo.oldpassword || '';
        dataInfo.password = dataInfo.password || '';
        dataInfo.repassword = dataInfo.repassword || '';
        if (!dataInfo.oldpassword) {
            return callback('原始密码不能为空');
        }
        if (!dataInfo.password) {
            return callback('新密码不能为空');
        }
        if (dataInfo.password !== dataInfo.repassword) {
            return callback('新密码与重复新密码不一致');
        }
        mui.post("/profile/updatepwd.html", dataInfo, function (data) {
            return callback(data.msg);
        }, "json");
    };
    owner.createState = function (name, callback) {
        var state = owner.getState();
        state.account = name;
        state.token = "token123456789";
        owner.setState(state);
        return callback();
    };
    /**
     * 新用户注册
     **/
    owner.regist = function (regInfo, callback) {
        callback = callback || $.noop;
        regInfo = regInfo || {};
        if (regInfo.username.length < 5) {
            return callback('用户名最短需要 5 个字符');
        }
        if (regInfo.password.length < 6) {
            return callback('密码最短需要 6 个字符');
        }
        mui.post("/site/signup.html", regInfo, function (data) {
            if (data.status === false) {
                return callback(data.msg);
            } else {
                window.location.href = data.url;
            }
        }, "json");
    };
    /**
     * 获取当前状态
     **/
    owner.getState = function () {
        var stateText = localStorage.getItem('$state') || "{}";
        return JSON.parse(stateText);
    };
    /**
     * 设置当前状态
     **/
    owner.setState = function (state) {
        state = state || {};
        localStorage.setItem('$state', JSON.stringify(state));
        //var settings = owner.getSettings();
        //settings.gestures = '';
        //owner.setSettings(settings);
    };
    var checkEmail = function (email) {
        email = email || '';
        return (email.length > 3 && email.indexOf('@') > -1);
    };
    /**
     * 找回密码
     **/
    owner.forgetPassword = function (email, callback) {
        callback = callback || $.noop;
        if (!checkEmail(email)) {
            return callback('邮箱地址不合法');
        }
        return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
    };
    /**
     * 获取应用本地配置
     **/
    owner.setSettings = function (settings) {
        settings = settings || {};
        localStorage.setItem('$settings', JSON.stringify(settings));
    };
    /**
     * 设置应用本地配置
     **/
    owner.getSettings = function () {
        var settingsText = localStorage.getItem('$settings') || "{}";
        return JSON.parse(settingsText);
    };
    /*
     * 记录新手指导显示情况
     */
    owner.handsHit = function () {
        var $settings = owner.getSettings();
        if ($settings.handhits === "undefined") {
            mui.extend($settings, {"handhits": 5});
        } else if ($settings.handhits > 0) {
            //弹出
            mui.alert('<div class="gonggaotip">亲，公众号做任务已经开通了，为了方便，微信扫描：下方二维码进入公众号进行做任务！<br /><img src="/images/qrcode.jpg"  width="158" height="158"/></div>', "活动公告", '朕，知道了')
            mui.extend($settings, {"handhits": $settings.handhits - 1});
        }
        owner.setSettings($settings);
    };
    /*
     * 首页广告滚动条
     * @returns {undefined}
     */
    owner.scrollNotice = function () {
        var that = jQuery("#scroll-notice");
        var scrollTimer;
        that.hover(function () {
            clearInterval(scrollTimer);
        }, function () {
            scrollTimer = setInterval(function () {
                var $self = that.find("ul");
                var lineHeight = $self.find("li:first").height();
                $self.animate({
                    "marginTop": -lineHeight + "px"
                }, "slow", "linear",function () {
                    $self.css({
                        marginTop: 0
                    }).find("li:first").appendTo($self);
                });
            }, 2000);
        }).trigger("mouseleave");
    };
    /*
     * 提现记录数据加载
     */
    owner.txrecordrefresh = function () {
        var page = 1;
        var pullfreshFunc = function () {
            var _self = this;
            mui.post('/account/ajaxtxrecord.html', {
                page: page
            }, function (data) {
                if (data) {
                    var $dataDiv = document.querySelector("#refreshContainer .mui-scroll ul");
                    $dataDiv.innerHTML = $dataDiv.innerHTML + data;
                    page++;
                    _self.endPullupToRefresh(false);
                } else {
                    _self.endPullupToRefresh(true);
                }
            }, 'text');
        };
        mui.init({
            pullRefresh: {
                container: "#refreshContainer", //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
                up: {
                    height: 50, //可选.默认50.触发上拉加载拖动距离
                    auto: true, //可选,默认false.自动上拉加载一次
                    contentrefresh: "正在加载...", //可选，正在加载状态时，上拉加载控件上显示的标题内容
                    contentnomore: '没有更多数据了', //可选，请求完毕若没有更多数据时显示的提醒内容；
                    callback: pullfreshFunc
                }
            }
        });
    };
    /*
     * 任务大厅
     */
    owner.taskwork = function (dataInfo) {
        var picker = new mui.PopPicker();
        picker.setData(dataInfo.pickerDict);
        picker.pickers[0].setSelectedValue(dataInfo.type, 2000);
        mui("#search-type").on("tap", "div", function () {
            picker.show(function (selectItems) {
                if (selectItems[0].value != dataInfo.type) {
                    window.location.href = "/task/work.html?type=" + selectItems[0].value;
                }
            });
        });
        var page = 1;
        var pullfreshFunc = function () {
            var _self = this;
            mui.post('/task/ajaxwork.html', {
                page: page,
                type: dataInfo.type
            }, function (data) {
                if (data) {
                    var $dataDiv = document.querySelector("#refreshContainer .mui-scroll ul");
                    $dataDiv.innerHTML = $dataDiv.innerHTML + data;
                    mui('#refreshContainer .mui-scroll ul li').on('tap', 'button', function (e) {
                        var targetTab = this.getAttribute('url');
                        mui(this).button('loading');
                        mui.post(targetTab, {}, function (data) {
                            if (data.status === true) {
                                window.location.href = data.url;
                            } else {
                                mui.toast(data.msg);
                                mui(this).button('reset');
                            }
                        }, 'json');
                    });
                    page++;
                    _self.endPullupToRefresh(false);
                } else {
                    _self.endPullupToRefresh(true);
                }
            }, 'text');
        };
        mui.init({
            pullRefresh: {
                container: "#refreshContainer", //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
                up: {
                    height: 50, //可选.默认50.触发上拉加载拖动距离
                    auto: true, //可选,默认false.自动上拉加载一次
                    contentrefresh: "正在加载...", //可选，正在加载状态时，上拉加载控件上显示的标题内容
                    contentnomore: '没有更多数据了', //可选，请求完毕若没有更多数据时显示的提醒内容；
                    callback: pullfreshFunc
                }
            }
        });
    };
    /*
     * 查询任务信息
     */
    owner.myworkinfo = function (conf) {
        var page = 1;
        var pullfreshFunc = function () {
            var _self = this;
            mui.post(conf.url, {
                page: page
            }, function (data) {
                if (data) {
                    var $dataDiv = document.querySelector("#refreshContainer .mui-scroll ul");
                    $dataDiv.innerHTML = $dataDiv.innerHTML + data;
                    mui('#refreshContainer .mui-scroll ul li').on('tap', 'button', function (e) {
                        var targetTab = this.getAttribute('url');
                        mui(this).button('loading');
                        window.location.href = targetTab;
                    });
                    page++;
                    _self.endPullupToRefresh(false);
                } else {
                    _self.endPullupToRefresh(true);
                }
            }, 'text');
        };
        mui.init({
            pullRefresh: {
                container: "#refreshContainer", //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
                up: {
                    height: 50, //可选.默认50.触发上拉加载拖动距离
                    auto: true, //可选,默认false.自动上拉加载一次
                    contentrefresh: "正在加载...", //可选，正在加载状态时，上拉加载控件上显示的标题内容
                    contentnomore: '没有更多数据了', //可选，请求完毕若没有更多数据时显示的提醒内容；
                    callback: pullfreshFunc
                }
            }
        });
    };
    /*
     * 任务详情
     */
    owner.taskdetail = function (conf) {
        //绑定隐藏按钮, //绑定报告按钮
        mui(".btn-operate").on("tap", "button", function (event) {
            var that = mui(this);
            var id = this.getAttribute('data-id');
            var action = this.getAttribute("data-action");
            var tips = this.getAttribute("data-tips");
            that.button('loading');
            mui.confirm(tips, function (e) {
                if (e.index > 0) {
                    mui.post("/task/hidetask.html", {id: id, action: action}, function (data) {
                        if (data.status) {
                            window.location.href = data.url;
                        } else {
                            mui.toast(data.msg);
                            that.button('reset');
                        }
                    }, 'json');
                } else {
                    that.button('reset');
                }
            });
        });
        //绑定图片并提交任务
        mui(".mui-card-footer").on("tap", "button", function (event) {
            var btnID = this.getAttribute("id");
            var that = mui(this);
            that.button("loading");
            if (btnID === "img_upload_submit") {
                wx.chooseImage({
                    // 默认9
                    count: conf.image_count,
                    // 可以指定是原图还是压缩图，默认二者都有
                    sizeType: ['original', 'compressed'],
                    // 可以指定来源是相册还是相机，默认二者都有
                    sourceType: ['album', 'camera'],
                    success: function (res) {
                        // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        if (res.localIds.length !== conf.image_count) {
                            mui.toast('对不起!图片上传数量不符，需要' + conf.image_count + '张');
                        } else {
                            mui('#upload_images')[0].innerHTML = "";
                            var image_arr = [];
                            for (var i = 0; i < res.localIds.length; i++) {
                                if (typeof (res.localIds[i]) !== "undefined") {
                                    var html = '<img height="150px" width="100%" src="' + res.localIds[i].toString() + '"/>';
                                    mui('#upload_images')[0].insertAdjacentHTML('beforeend', html);
                                    wx.uploadImage({
                                        localId: res.localIds[i].toString(),
                                        // 默认为1，显示进度提示
                                        isShowProgressTips: 1,
                                        success: function (e) {
                                            // 返回图片的服务器端ID
                                            image_arr.push(e.serverId);
                                            if (i === parseInt(conf.image_count)) {
                                                mui.post("/task/taskdetail.html", {id: conf.id, images: image_arr.join(",")}, function (data) {
                                                    if (data.status === true) {
                                                        window.location.href = data.url;
                                                    } else {
                                                        mui.toast(data.msg);
                                                        that.button("reset");
                                                    }
                                                }, 'json');
                                            }
                                        }
                                    });
                                }
                            }
                        }
                        that.button("reset");
                    },
                    cancel: function () {
                        that.button("reset");
                    }
                });
            }
        });
    };
}(mui, window.app = {}));